<template>
  <canvas ref="canvasRef"></canvas>
</template>
  
  <script setup>
import * as Three from "three";
import { onMounted, ref } from "vue";

const canvasRef = ref(null);

onMounted(() => {
  // console.log(canvasRef.value);

  // 创建渲染器
  const renderer = new Three.WebGLRenderer({ canvas: canvasRef.value });
  renderer.setClearColor(0xadd8e6, 1);

  // 创建场景
  const scene = new Three.Scene();
  // scene.fog = new Three.Fog(0xadd8e6,1,2);
  scene.fog = new Three.FogExp2(0xadd8e6, 0.8);

  // 创建镜头
  const camera = new Three.PerspectiveCamera(75, 2, 0.1, 5);

  // 创建几何体
  const geometry = new Three.BoxGeometry(1, 1, 1);

  //创建材质
  const meterial1 = new Three.MeshPhongMaterial({ color: 0x44aa88 });
  const meterial2 = new Three.MeshPhongMaterial({ color: 0xc50d0d });
  const meterial3 = new Three.MeshPhongMaterial({ color: 0x39b20a });

  // 创建网格
  const cube1 = new Three.Mesh(geometry, meterial1); // 将材质作用于几何体
  cube1.position.x = -1.5;
  scene.add(cube1); // 向场景里面添加网格

  const cube2 = new Three.Mesh(geometry, meterial2); // 将材质作用于几何体
  scene.add(cube2);

  const cube3 = new Three.Mesh(geometry, meterial3); // 将材质作用于几何体
  cube3.position.x = 1.5;
  scene.add(cube3);

  const cubes = [cube1, cube2, cube3];

  // 创建光源
  const light = new Three.DirectionalLight(0xffffff, 1);
  light.position.set(-1, 2, 4);
  scene.add(light); // 向场景里面添加灯光

  camera.position.z = 2;

  cubes[1].material.fog = false;

  // 渲染出来
  renderer.render(scene, camera);

  // 自动旋转
  const rotate = (time) => {
    time = time * 0.001;
    cubes.map((cube) => {
      cube.rotation.x = time;
      cube.rotation.y = time;
    });
    // cube1.rotation.x = time;
    // cube1.rotation.y = time;
    // cube2.rotation.x = time;
    // cube2.rotation.y = time;
    // cube3.rotation.x = time;
    // cube3.rotation.y = time;
    renderer.render(scene, camera);
    window.requestAnimationFrame(rotate);
  };
  window.requestAnimationFrame(rotate);

  // 窗口发生变化
  const handleResize = () => {
    const canvas = renderer.domElement; // 获取到canvas
    // console.log(canvas.offsetWidth); // 或者clientWidth
    camera.aspect = canvas.clientWidth / canvas.clientHeight; // 设置镜头的宽高比
    camera.zoom = 0.5 * (canvas.clientWidth / canvas.clientHeight);
    camera.updateProjectionMatrix(); // 通知镜头改变宽高比
    renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
  };

  handleResize();
  // 屏幕窗口自适应
  window.addEventListener("resize", handleResize);
});
</script>
  
  <style scoped>
canvas {
  display: block;
  width: inherit; /* 继承父容器宽度  */
  height: inherit;
}
</style>